package com.qingcloud.adminbackend.controller;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.ImmutableMap;
import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.entity.config.SysSensorFactorConfig;
import com.qingcloud.adminbackend.entity.equipment.EquipmentNewBaseDataDTO;
import com.qingcloud.adminbackend.entity.equipment.ModelDTO;
import com.qingcloud.adminbackend.entity.weatherdata.WeatherBO;
import com.qingcloud.adminbackend.entity.weatherdata.WeatherDTO;
import com.qingcloud.adminbackend.entity.weatherdata.WeatherExportBO;
import com.qingcloud.adminbackend.mapper.SysSensorFactorConfigMapper;
import com.qingcloud.adminbackend.service.IWeatherDataService;
import com.qingcloud.adminbackend.service.impl.BaseServiceImpl;
import com.qingcloud.adminbackend.utils.CookieUtil;
import com.qingcloud.adminbackend.utils.PoiExcelExport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(value = "原始数据管理", description = "原始数据管理")
@RestController
@RequestMapping("/weatherdata")
public class WeatherDataController {

    @Resource
    private IWeatherDataService weatherDataService;
    @Resource
    private BaseServiceImpl baseService;
    @Resource
    private SysSensorFactorConfigMapper sysSensorFactorConfigMapper;
    @Value("${file.rootpath}")
    private String ROOTPATH;

    @ApiOperation(value = "原始数据列表API", notes = "原始数据列表API", response = WeatherDTO.class)
    @PostMapping("/findWeatherData")
    public AjaxResult findWeatherData(@RequestBody WeatherBO weatherBO, HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        int stationFlag = weatherBO.getEquipmentPoolFlag() == null ? 0 : Integer.valueOf(weatherBO.getEquipmentPoolFlag());
        List<ModelDTO> equipments = baseService.getEquipmentIds(userId, weatherBO.getOrderIds(), weatherBO.getOrgIds(), stationFlag);
        if (equipments.size() == 0) {
            return new AjaxResult(WamingConstant.SUCCESS, "", "");
        }
        List<String> equipmentIds = new ArrayList<>();
        equipments.forEach(equipment -> {
            equipmentIds.add(equipment.getModelId());
        });
        return new AjaxResult(WamingConstant.SUCCESS, "", weatherDataService.getWeatherData(weatherBO, equipmentIds));
    }

    @ApiOperation(value = "导出站点数据", notes = "导出站点数据")
    @PostMapping(value = "/exportStationData")
    public AjaxResult exportData(@RequestBody WeatherExportBO weatherBO, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String fileName = "RawDataFile-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".xlsx";
        String sheetName = "原始数据";
        String userId = CookieUtil.getUserId(request);
        int stationFlag = weatherBO.getEquipmentPoolFlag() == null ? 0 : Integer.valueOf(weatherBO.getEquipmentPoolFlag());
        List<ModelDTO> equipments = baseService.getEquipmentIds(userId, weatherBO.getOrderIds(), weatherBO.getOrgIds(), stationFlag);
        List<String> equipmentIds = new ArrayList<>();
        equipments.forEach(equipment -> {
            equipmentIds.add(equipment.getModelId());
        });
        //监测因子内容描述map
        List<SysSensorFactorConfig> configs = sysSensorFactorConfigMapper.selectByMap(ImmutableMap.of());
        //监测因子内容描述map
        Map<Integer, String> mapDesc = configs.stream().collect(Collectors.toMap(SysSensorFactorConfig::getFactorId, SysSensorFactorConfig::getFactorDesc));
        Map<String, String> mapContent = configs.stream().collect(Collectors.toMap(SysSensorFactorConfig::getFactorDesc, SysSensorFactorConfig::getFactorContent));
        List<String> list = baseService.getFactorDetails(mapDesc, weatherBO.getFactors());
        String[] titleName = {"设备编号", "时间", "监测点编号", "经度", "纬度", "监测点名称", "省/市/区县"};// 列名
        String[] titleColumn = {"equipmentId", "rtcTime", "stationId", "lng", "lat", "stationName", "domainDetails"};
        int[] titleSize = {10, 20, 10, 15, 15, 10, 10};
        if (list.size() > 0) {
            titleName = arrayToString(titleName, list, null, "(原始值)", "(应用值)", "(实验值)");
            titleColumn = arrayToString(titleColumn, list, mapContent, "Raw", "", "Lab");
            titleSize = new int[titleColumn.length];
            for (int j = 0; j < titleColumn.length; j++) {
                titleSize[j] = 10;
            }
        }
        String fileDir = ROOTPATH + "/temp";
        File dir = new File(fileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String file = fileDir + "/" + fileName;
        List<EquipmentNewBaseDataDTO> srcBos = weatherDataService.getWeatherDataList(weatherBO, equipmentIds);
        PoiExcelExport poiExcelExport = new PoiExcelExport(file, sheetName);
        poiExcelExport.wirteExcel(titleColumn, titleName, titleSize, srcBos);
        AjaxResult result = new AjaxResult();
        String url = request.getContextPath() + "/file/view/temp/" + fileName;
        Map<String, String> resultMap = new HashMap<>(1);
        resultMap.put("url", url);
        result.setResult(resultMap);
        result.setErroCode(2000);
        return result;
    }

    public String[] arrayToString(String[] array, List<String> list, Map<String, String> mapContent, String x, String y, String z) {
        for (String it : list) {
            int index = array.length;
            array = insertElement(array, it, index, x, y, z, mapContent);
        }
        return array;
    }

    public static String[] insertElement(String original[], String element, int index, String x, String y, String z, Map<String, String> mapContent) {
        int length = original.length;
        String destination[] = new String[length + 3];
        System.arraycopy(original, 0, destination, 0, length);
        if (StrUtil.isNotBlank(y)) {
            destination[index] = element.concat(x);
            destination[index + 1] = element.concat(y);
            destination[index + 2] = element.concat(z);
        } else {
            element = mapContent.get(element);
            if ("HUM".equals(element)) {
                element = "humidity";
            } else if ("TEMP".equals(element)) {
                element = "temperature";
            } else if ("WINDDIRECT".equals(element)) {
                element = "windDirection";
            } else if ("WINDPOWER".equals(element)) {
                element = "windPower";
            } else {
                element = element.toLowerCase();
            }
            destination[index] = element.concat(x);
            destination[index + 1] = element.concat(y);
            destination[index + 2] = element.concat(z);
        }
        return destination;
    }
}
